//
//  BSKMapViewController.m
//  MicroMemory
//
//  Created by rimi on 16/7/20.
//  Copyright © 2016年 BlueSky. All rights reserved.
//

#import "BSKMapViewController.h"
#import "UIViewController+BSKToast.h"
#import "BSKNote.h"
#import <UIView+SDAutoLayout.h>
#import "BSKconsts.h"
#import "BSKTheme.h"
@import MapKit;
@import CoreLocation;
#import "BSKAnnotationView.h"
#import "BSKPointAnnotation.h"
#import "BSKNoteViewController.h"


@interface BSKMapViewController ()<MKMapViewDelegate,CLLocationManagerDelegate>
@property(nonatomic,strong)MKMapView * myMapView;
@property(nonatomic,strong)CLLocationManager * locationManager;
@end

@implementation BSKMapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
	[self.locationManager startUpdatingLocation];
	self.locationManager.delegate = self;
	[self loadUI];
}
-(void)viewWillAppear:(BOOL)animated{
	[self loadNotes];
}
-(void)loadUI{
	[self.view addSubview: self.myMapView ];
	
	UIBlurEffect * efect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
	UIVisualEffectView * titleView = [[UIVisualEffectView alloc]initWithEffect:efect];
	CGFloat r=0,g=0,b=0,a=0;
	[[BSKTheme curentTheme].themeColor getRed:&r green:&g blue:&b alpha:&a];
	
	titleView.backgroundColor = [UIColor colorWithRed:r green:g blue:b alpha:0.5];
	[self.view addSubview:titleView];
	titleView.sd_layout
		.topSpaceToView(self.view,0)
		.leftSpaceToView(self.view,0)
		.rightSpaceToView(self.view,0)
		.heightIs(StatusBarHeight+NavigationBarHeight);
	UIButton * backbutton = [UIButton buttonWithType:UIButtonTypeCustom];
	[backbutton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
	[backbutton addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:backbutton];
	backbutton.sd_layout
		.leftSpaceToView(self.view,10)
		.topSpaceToView(self.view,StatusBarHeight + 5)
		.heightIs(NavigationBarHeight - 10)
		.widthEqualToHeight();
	backbutton.imageEdgeInsets = UIEdgeInsetsMake(3, 3, 3, 3);
	UILabel * titleLabel = [[UILabel alloc]init];
	[self.view addSubview:titleLabel];
	titleLabel.text = @"记忆足迹";
	titleLabel.textAlignment = NSTextAlignmentCenter;
	titleLabel.sd_layout
    .centerXEqualToView(self.view)
    .centerYEqualToView(backbutton);
    titleLabel.font = [UIFont systemFontOfSize:20];
	titleLabel.textColor = [UIColor whiteColor];
    [titleLabel sizeToFit];
}

-(void)backAction:(UIButton *)sender{
	[self.navigationController popViewControllerAnimated:YES];
}

-(void)loadNotes{
	[self.myMapView removeAnnotations:self.myMapView.annotations];
	NSMutableArray * Annotations = [NSMutableArray array];
	for (NSInteger index = 0;index<_noteList.count;index++) {
		BSKNote * note  = _noteList[index];
		BSKPointAnnotation * notePoint = [[BSKPointAnnotation alloc]init];
		notePoint.title = note.title;
		notePoint.subtitle = note.address;
		notePoint.noteIndex = index;
		notePoint.coordinate = CLLocationCoordinate2DMake(note.latitude, note.longitude);
		[self.myMapView addAnnotation:notePoint];
		[Annotations addObject:notePoint];
	}
	[self.myMapView setSelectedAnnotations:Annotations];
}
#pragma mark MKMapViewDelegate

-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
	
	if ([annotation isKindOfClass:[MKUserLocation class]]) {
		return nil;
	}
	
	BSKAnnotationView * view =(BSKAnnotationView * )[mapView dequeueReusableAnnotationViewWithIdentifier:@"123"];
	if (!view) {
		view = [[BSKAnnotationView alloc]initWithAnnotation: annotation reuseIdentifier:@"123"];
	}
	BSKPointAnnotation * notePoint = (BSKPointAnnotation *) annotation;
	view.noteIndex = notePoint.noteIndex;
	__weak typeof(self) weakself = self;
	[view setClickCallback:^(NSInteger index) {
		[weakself click:index];
	}];
	return view ;
}

-(void)click:(NSInteger)index{
	BSKNoteViewController * noteVC = [[BSKNoteViewController alloc]init];
	noteVC.CurentNote = _noteList[index];
	noteVC.isNewNote = NO;
	noteVC.dbManager = _manager;
	[self.navigationController pushViewController:noteVC animated:YES];
}
#pragma mark 定位
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
	[manager stopUpdatingLocation];
	CLLocation * location = [locations firstObject];
	MKCoordinateSpan span = MKCoordinateSpanMake(0.01, 0.01);
	CLLocationCoordinate2D coordinate = location.coordinate;
	MKCoordinateRegion regin = MKCoordinateRegionMake(coordinate, span);
	[_myMapView setRegion:regin animated:YES];
	_myMapView.userLocation.title = @"我的位置";
	CLGeocoder * coder = [[CLGeocoder alloc]init];
	[coder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
		if (error) {
			NSLog(@"%@",error);
			return ;
		}
		CLPlacemark * placeMark = [placemarks firstObject];
		NSDictionary * addressDic = placeMark.addressDictionary;
		_myMapView.userLocation.subtitle = [NSString stringWithFormat:@"%@",[addressDic[@"FormattedAddressLines"] firstObject]];
	}];
}
#pragma mark getter
-(MKMapView *)myMapView{
	if (_myMapView) {
		return _myMapView;
	}
	_myMapView = [[MKMapView alloc]initWithFrame:self.view.bounds];
	_myMapView.mapType = MKMapTypeStandard;
	//显示用户所在位置
	_myMapView.showsUserLocation = YES;
	_myMapView.delegate = self;

	return _myMapView;
}

-(CLLocationManager *)locationManager{
	if (_locationManager) {
		return _locationManager;
	}
	if (![CLLocationManager locationServicesEnabled]) {
		[self MakeToast:@"定位不可用，请检查设置" WithTime:3];
	}
	_locationManager = [[CLLocationManager alloc]init];
	[_locationManager requestWhenInUseAuthorization];
	_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
	_locationManager.distanceFilter = kCLHeadingFilterNone;
	return _locationManager;
}
@end
